Here’s a cleaner and easier-to-read version of your write-up. I’ve reorganized and simplified some of the explanations while preserving all technical details:
---
## Blocking `.env` File Access
The `.env` file should never be accessible via a web browser. Most web servers already block hidden files (dotfiles) by default — but it’s still a good idea to be explicit.
---
### Apache
#### Option 1: Block `.env` directly in `.htaccess`:
```apache
# Disable directory listing
Options -Indexes
# Block access to .env file
Order allow,deny
Deny from all
```
> ✅ The key directive here is ``.
#### Option 2: Block all dotfiles explicitly:
```apache
# Disable directory listing
Options -Indexes
# Block all hidden files (starting with a dot)
Order allow,deny
Deny from all
```
> ✅ This is the better option
---
### Nginx
In your server block (vhost) or a config it includes, add this to block dotfiles:
```nginx
location ~ /\. {
deny all;
access_log off;
error_log /var/log/nginx/blocked_dotfile.log;
}
```
---
## Directory Indexing Behavior
### Apache
- **Default behavior:** Directory indexing is **enabled**.
- Apache **does hide** dotfiles (like `.env`) when listing directories.
> 📌 You should disable indexing to avoid listing files:
```apache
Options -Indexes
```
---
### Nginx
- **Default behavior:** Directory indexing is **disabled**.
- But if directory indexing is **enabled manually**, dotfiles **are shown** in the listing (which is dangerous).
> ❗ Even if `.env` is blocked from direct access, showing it in a directory listing may tip off attackers to its location. Then the hacker can try to access the .env file in ways that the vhost denying the file won't be able to block (eg. LFI with Directory Traversal vulnerability if your app gets supplied a filename to show its content through a url search param)
---
## Safer Custom Directory Listing (PHP Example)
To list files in a folder _without_ exposing hidden files or `.env`, you can use a custom script like this:
```
Index of = htmlspecialchars(basename($dir)) ?>/
Index of = htmlspecialchars($_SERVER['REQUEST_URI']) ?>